package self.zhangkang.chart.view.pool

import android.graphics.Path
import androidx.core.util.Pools

/**
 * @author : Android-张康
 * created on: 2023/5/6 15:55
 * description: Path 对象池
 */
class PathPool(maxPoolSize: Int = 16) : Pools.Pool<Path> {

    private val mPool: Array<Any?>

    private var mPoolSize = 0

    init {
        require(maxPoolSize > 0) {
            "The max pool size must be > 0"
        }
        mPool = arrayOfNulls(maxPoolSize)
    }

    override fun acquire(): Path {
        if (mPoolSize > 0) {
            val lastPooledIndex = mPoolSize - 1
            val instance: Path? = mPool[lastPooledIndex] as Path?
            mPool[lastPooledIndex] = null
            mPoolSize--
            return instance?.apply {
                reset()
            } ?: Path().apply {
                reset()
            }
        }
        return Path().apply {
            reset()
        }
    }

    override fun release(instance: Path): Boolean {
        check(!isInPool(instance)) {
            var index = 0
            for (i in 0 until mPoolSize) {
                if (mPool[i] === instance) {
                    index = i
                    break
                }
            }
            "Already in the pool! instance = $instance index = $index"
        }
        if (mPoolSize < mPool.size) {
            mPool[mPoolSize] = instance
            mPoolSize++
            return true
        }
        return false
    }

    private fun isInPool(instance: Path): Boolean {
        for (i in 0 until mPoolSize) {
            if (mPool[i] === instance) {
                return true
            }
        }
        return false
    }
}